package com.example.lexiangbackend.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Component
public class FileUtil {

    @Value("${file.upload.path:lexiangbackend/src/main/uploads}")
    private String fileUploadPath;

    /**
     * 删除音乐相关文件
     */
    public void deleteMusicFiles(String musicFilePath, String coverFilePath) {
        if (musicFilePath != null && !musicFilePath.isEmpty()) {
            deleteFileFromUrl(musicFilePath, "songs");
        }
        if (coverFilePath != null && !coverFilePath.isEmpty()) {
            deleteFileFromUrl(coverFilePath, "covers");
        }
    }

    /**
     * 根据URL删除文件
     */
    public boolean deleteFileFromUrl(String fileUrl, String fileType) {
        try {
            String fileName = extractFileNameFromUrl(fileUrl);
            if (fileName == null) {
                return false;
            }

            String fullPath = fileUploadPath + "/" + fileType + "/" + fileName;
            Path path = Paths.get(fullPath);
            
            if (Files.exists(path)) {
                Files.delete(path);
                System.out.println("成功删除文件: " + fullPath);
                return true;
            } else {
                System.out.println("文件不存在: " + fullPath);
                return false;
            }
        } catch (IOException e) {
            System.err.println("删除文件失败: " + fileUrl + ", 错误: " + e.getMessage());
            return false;
        }
    }

    /**
     * 从URL中提取文件名
     */
    public String extractFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }

        // 如果是完整URL（如：http://localhost:2025/api/files/songs/filename.mp3）
        if (url.startsWith("http://") || url.startsWith("https://")) {
            int lastSlash = url.lastIndexOf('/');
            if (lastSlash >= 0 && lastSlash < url.length() - 1) {
                return url.substring(lastSlash + 1);
            }
        }
        // 如果是API路径（如：/api/files/songs/filename.mp3）
        else if (url.startsWith("/api/files/")) {
            int lastSlash = url.lastIndexOf('/');
            if (lastSlash >= 0 && lastSlash < url.length() - 1) {
                return url.substring(lastSlash + 1);
            }
        }
        // 如果是相对路径或直接的文件名
        else {
            int lastSlash = Math.max(url.lastIndexOf('/'), url.lastIndexOf('\\'));
            if (lastSlash >= 0 && lastSlash < url.length() - 1) {
                return url.substring(lastSlash + 1);
            }
            return url;
        }

        return null;
    }

    /**
     * 判断是否为音频文件
     */
    public boolean isAudioFile(String fileName) {
        if (fileName == null) return false;
        String lowerName = fileName.toLowerCase();
        return lowerName.endsWith(".mp3") || lowerName.endsWith(".wav") || 
               lowerName.endsWith(".flac") || lowerName.endsWith(".aac") || 
               lowerName.endsWith(".ogg") || lowerName.endsWith(".m4a");
    }

    /**
     * 判断是否为图片文件
     */
    public boolean isImageFile(String fileName) {
        if (fileName == null) return false;
        String lowerName = fileName.toLowerCase();
        return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || 
               lowerName.endsWith(".png") || lowerName.endsWith(".gif") || 
               lowerName.endsWith(".webp");
    }

    /**
     * 获取文件类型目录
     */
    public String getFileTypeDirectory(String fileName) {
        if (isAudioFile(fileName)) {
            return "songs";
        } else if (isImageFile(fileName)) {
            return "covers";
        }
        return null;
    }
} 